package com.per.note.ui.floatball;

import android.content.Context;
import android.graphics.PixelFormat;
import android.view.Gravity;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;

public class MyWindowManager{
	private static FloatWindowView fWindow;
	private static LayoutParams fWindowParams;
	// 用于控制在屏幕上添加或移除悬浮窗
	private static WindowManager mWindowManager;

	/**
	 * 创建一个悬浮窗。初始位置为屏幕的右部中间位置。
	 * @param context
	 * 必须为应用程序的Context.
	 */
	public static void createWindow(Context context) {
		WindowManager windowManager = getWindowManager(context);
		int screenWidth = windowManager.getDefaultDisplay().getWidth();
		int screenHeight = windowManager.getDefaultDisplay().getHeight();
		if (fWindow == null) {
			fWindow = new FloatWindowView(context);
			if (fWindowParams == null) {
				fWindowParams = new LayoutParams();
				fWindowParams.type = LayoutParams.TYPE_PHONE;
				fWindowParams.format = PixelFormat.RGBA_8888;
				fWindowParams.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL
						| LayoutParams.FLAG_NOT_FOCUSABLE;
				fWindowParams.gravity = Gravity.LEFT | Gravity.TOP;
				fWindowParams.width = FloatWindowView.viewWidth;
				fWindowParams.height = FloatWindowView.viewHeight;
				fWindowParams.x = screenWidth;
				fWindowParams.y = screenHeight / 2;
			}
			fWindow.setParams(fWindowParams);
			windowManager.addView(fWindow, fWindowParams);
		}
	}
	/**
	 * 将悬浮窗从屏幕上移除。
	 */
	public static void removeWindow(Context context) {
		if (fWindow != null) {
			WindowManager windowManager = getWindowManager(context);
			windowManager.removeView(fWindow);
			fWindow = null;
		}
	}

	/**
	 * 是否有悬浮窗显示在屏幕上。
	 * 有悬浮窗显示在桌面上返回true，没有的话返回false。
	 */
	public static boolean isWindowShowing() {
		return fWindow != null ;
	}

	/**
	 * 如果WindowManager还未创建，则创建一个新的WindowManager返回。否则返回当前已创建的WindowManager。
	 * @return WindowManager的实例，用于控制在屏幕上添加或移除悬浮窗。
	 */
	private static WindowManager getWindowManager(Context context) {
		if (mWindowManager == null) {
			mWindowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
		}
		return mWindowManager;
	}
}
